package com.dome.gateway.config;

import com.dome.auth.UserContextHolder;
import com.dome.gateway.route.GatewayApiRoute;
import com.dome.gateway.route.GatewayApiRouteProperties;
import com.dome.util.constans.CommonConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @author: hz
 * @time: 2021/4/28 17:01
 */
@Component
@Slf4j
public class GrayFilter extends ZuulFilter {

    @Autowired
    private GatewayApiRouteProperties gatewayApiRouteProperties;
    //是否设置了网关版本.在没有header会使用配置version
    @Value("${spring.cloud.nacos.discovery.metadata.version:}")
    private String metadata_version;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1000;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String version = ctx.getRequest().getHeader(CommonConstants.CONTEXT_KEY_VERSION);
        if(StringUtils.isNotBlank(version)) {
            for(GatewayApiRoute gatewayApiRoute : gatewayApiRouteProperties.getGatewayApiRoutes().values()){
                if(gatewayApiRoute.getVersions()!=null&&
                        gatewayApiRoute.getVersions().contains(version)&&
                        gatewayApiRoute.getServiceId().equals(ctx.get("serviceId"))) {
                    //如果服务配置了版本 就能指向过去
                    log.info("GrayFilter=====>version:{}", version);
                    // 传递给后续微服务
                    ctx.addZuulRequestHeader(CommonConstants.CONTEXT_KEY_VERSION, version);
                    UserContextHolder.getInstance().setVersion(version);
                    return null;
                }
            }
        } else {
            if(StringUtils.isNotBlank(metadata_version)) {
                //如果头部没有传输 可以直接使用配置version进行传输
                log.info("GrayFilter=====>metadata_version:{}", metadata_version);
                ctx.addZuulRequestHeader(CommonConstants.CONTEXT_KEY_VERSION, metadata_version);
                UserContextHolder.getInstance().setVersion(metadata_version);
                return null;
            }
        }

        return null;
    }
}